/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package andreafrancia.util;

import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;

/**
 *
 * @author Andrea
 */
public class LoggingDecorators {
    private static final Logger logger = 
            Logger.getLogger(LoggingDecorators.class.getName());
    
    public static <T> T loggingDecorator(
                final T target,
                final Class<T> targetClass) {
        return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), 
                new Class[] { targetClass}, new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                logger.info("Begin of " + method);
                try {
                    return method.invoke(target, args);
                } catch(InvocationTargetException ex) {
                    throw ex.getCause();
                } finally {
                    logger.info("End of " + method);
                }
            }
        });
    }
    
    public static void main(String[] args) {
        MouseListener target = new MouseAdapter() {};
        MouseListener decorator = LoggingDecorators.loggingDecorator(target, MouseListener.class);
        decorator.mouseClicked(null);
    }
}
